<template>
  <div v-if="isShow">
    <goodsSwiper v-if="goodsInfo.data" :res="goodsInfo" />
    <div card p-36rpx>
      <div flex flex-a-c flex-j-sb>
        <div>
          <!-- 普通商品 -->
          <div text-46rpx font-700 text-main-color>{{ unitPrice(goodsInfo.data.price, '￥')
            }}</div>
        </div>
        <div flex text-24rpx gap-24rpx>
          <div flex flex-col flex-a-c>
            <nut-icon name="share-n" @click="share"></nut-icon>
            <span>分享</span>
          </div>
        </div>
      </div>
      <div font-bold text-30rpx my-20rpx>{{ goodsInfo.data.goodsName }}</div>
      <div color-warmGray text-24rpx>
        {{ goodsInfo.data.sellingPoint || "" }}
      </div>

      <div text-center my-auto flex flex-j-c>
        <div v-if="memberVOS.length">
          <nut-avatar-group span="-4">
            <nut-avatar v-for="(item, index) in memberVOS" :key="index">
              <image :src="item.face || '/static/default.png'" />
            </nut-avatar>
          </nut-avatar-group>
        </div>
      </div>
      <div v-if="master.toBeGroupedNum" text-center text-30rpx mt-40rpx>
        还差<span text-40rpx font-bold text-main-color> {{ master.toBeGroupedNum }}</span>人，赶快邀请好友拼单吧
      </div>

      <div v-if="isBuy && master.toBeGroupedNum <= 0" text-center text-30rpx mt-40rpx>
        已成功拼团
      </div>

      <div v-if="!isOver && master.toBeGroupedNum > 0">
        <nut-countdown v-if="goodsInfo?.data" v-model="resetTime"
          :end-time="getCountDownTime(goodsInfo?.data?.endTime)">
          <div mt-20rpx w-full flex flex-a-c flex-j-c mt-10rpx text-30rpx>
            <div color-white px-4rpx bg-main-color rounded>{{ resetTime.d }}</div>
            <span>天</span>
            <div color-white px-4rpx bg-main-color rounded>{{ resetTime.h }}</div>
            <span>时</span>
            <div color-white px-4rpx bg-main-color rounded>{{ resetTime.m }}</div>
            <span>分</span>
            <div color-white px-4rpx bg-main-color rounded>{{ resetTime.s }}</div>
            <span>秒</span>
          </div>
        </nut-countdown>
      </div>
    </div>
    <div position-fixed bottom-0 bg-white w-full flex justify-center>
      <div p-32rpx w-full>
        <div v-if="isMaster && !isOver">
          <nut-button block v-if="master.toBeGroupedNum" type="primary" @click="share">邀请好友拼团</nut-button>
        </div>
        <nut-button block v-if="!isMaster && !isOver && !isBuy" @click="buy" type="warning">立即购买</nut-button>
        <nut-button v-if="!isMaster && !isOver && isBuy" block type="primary" disabled>已购买该商品</nut-button>
        <div v-if="isOver" text-center text-main-color>拼团活动已结束</div>
      </div>
    </div>
    <shareModel ref="shareRef" />
    <nut-toast ref="toastRef" />
  </div>
</template>

<script setup lang="ts">
import storage from '@/utils/storage'
import { onLoad, onShareAppMessage } from '@dcloudio/uni-app';
import { getGroupBuyShare } from '@/api/promotion'
import { unitPrice } from '@/utils/filters'
import { billOrder } from '@/api/trade';
import shareModel from '@/components/share/index.vue';
import type { ToastInst } from 'nutui-uniapp';
import goodsSwiper from '@/components/goods/template/goods-swiper.vue'; //商品轮播
const routerVal = ref<any>('')
const memberVOS = ref<any>([])
const master = ref<any>('')
// 商品详情
const goodsInfo = ref<any>({
  data: ""
})
const isShow = ref<any>(false)
const shareRef = ref<any>('')
const isBuy = ref<boolean>(false)
const isOver = ref<boolean>(false)
const isMaster = ref<boolean>(false)
const resetTime = ref<any>({})
const toastRef = ref<ToastInst>()
onShareAppMessage((res: any) => {
  return {
    title: shareRef.value.shareTitle(),
    path: linkPath(),
    imageUrl: goodsInfo.value.data.thumbnail
  }
})
const linkPath = () => {
  return `/pages/mine/order/share?sn=${routerVal.value.sn}&skuId=${routerVal.value.skuId}&goodsId=${routerVal.value.goodsId}`
}

// 分享
function share() {
  shareRef.value.fill(
    {
      title: goodsInfo.value.data.goodsName,
      href: linkPath(),
      imageUrl: goodsInfo.value.data.thumbnail,
      type: 'pintuan'
    }
  )
  shareRef.value.open()
}


async function init(sn: string, skuId: string) {
  isShow.value = true
  const res = await getGroupBuyShare(sn, skuId)
  if (res.data.success) {
    goodsInfo.value.data = res.data.result.promotionGoods
    goodsInfo.value.data.goodsGalleryList = res.data.result.promotionGoods.thumbnail.split(',')
    memberVOS.value = res.data.result.pintuanMemberVOS


    // 获取剩余拼团人数
    master.value =
      res.data.result.pintuanMemberVOS.length != 0 &&
      res.data.result.pintuanMemberVOS.filter((item: any) => {
        return item.orderSn == "";
      })[0];

    let endTime: any = Date.parse(
      res.data.result.promotionGoods.endTime.replace(/-/g, "/")
    );
    // 获取当前剩余的拼团商品时间
    let timeStamp: any = Date.parse(new Date(endTime)) / 1000;

    // 获取当前时间时间戳
    let dateTime: any = Date.parse(new Date()) / 1000;

    timeStamp = parseInt(timeStamp - dateTime);

    timeStamp <= 0 ? (isOver.value = true) : (isOver.value = false);

    // // 获取当前是否是拼团本人
    if (
      storage.getUserInfo().id ==
      master.value.memberId
    ) {
      isMaster.value = true;
    } else {
      isMaster.value = false;

    }
    console.log(storage.getUserInfo().id)
    // 获取当前商品是否已经购买
    if (storage.getUserInfo().id) {
      let buy = res.data.result.pintuanMemberVOS.filter((item: any) => {
        return item.memberId == storage.getUserInfo().id;
      });

      buy.length ? isBuy.value = true : isBuy.value = false;
    }
  }
}

async function buy() {
  let data = {
    skuId: routerVal.value.skuId,
    num: 1,
    cartType: 'PINTUAN'
  };
  toastRef.value?.showToast['loading']('加载中', {
    cover: true,
    duration: 0
  })
  const res = await billOrder(data);
  if (res.data.success) {
    toastRef.value?.hideToast();
    uni.navigateTo({
      url: `/pages/mine/order/fillorder?way=${data.cartType}&parentOrderSn=${routerVal.value.sn}`
    });
  }
  else {
    toastRef.value?.hideToast();
  }
}


// 倒计时
const getCountDownTime = (val: string) => {

  let date = new Date(val);
  let timeSimple = new Date(date).getTime();

  return timeSimple
}

interface Options {
  skuId: string,
  goodsId: string,
  sn: string
}


onLoad((option: any) => {
  routerVal.value = option
  init(option.sn, option.skuId)
});
</script>

<style scoped></style>
